﻿using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using Bookkeeping.Persistence.Mappings;
using Bookkeeping.Persistence.Conventions;
using NHibernate.Tool.hbm2ddl;
using System.IO;
using System.Reflection;

namespace Bookkeeping.Persistence
{
    public class SessionFactorySingleton
    {
        private static ISessionFactory sessionFactory;

        public static ISessionFactory SessionFactory
        {
            get
            {
                if (sessionFactory == null)
                {
                    sessionFactory = Fluently.Configure()
                        .Mappings(x => x
                            .FluentMappings.AddFromAssemblyOf<PostMap>()
                            .Conventions.AddFromAssemblyOf<IdConvention>()
                            //.ExportTo(@"c:\temp\mappings")
                            )
                        .Database(MsSqlConfiguration.MsSql2005.ConnectionString(x => x
                            .Database("Bookkeeping")
                            .Server(@".\SQLEXPRESS")
                            .TrustedConnection())
                            .ShowSql())
                        .ExposeConfiguration(c =>
                            {
                                //new SchemaExport(c).Create(true, true);
                            })
                        .BuildSessionFactory();
                }

                return sessionFactory;
            }
        }

        public static ISession OpenSession()
        {
            return SessionFactory.OpenSession();
        }
    }
}
